package handler

import (
	"context"
	"fmt"
	"gitee.com/zaiqiang231/zcamp-service-user/app/http/service"
	"gitee.com/zaiqiang231/zcamp-service-user/app/rpc/proto"
	"gitee.com/zaiqiang231/zcamp-service-user/app/store"
	"sync"
)

var (
	userSever     *UserServer
	onceUserSever sync.Once
)

type UserServer struct {
}

func GetUserServer() (*UserServer, error) {
	onceUserSever.Do(func() {
		userSever = &UserServer{}
	})

	if userSever == nil {
		return nil, fmt.Errorf("got nil server")
	}

	return userSever, nil
}

func (s *UserServer) GetUserInfo(ctx context.Context, r *proto.UserInfoRequest) (*proto.UserInfoResponse, error) {
	user, err := store.GetUserStore().GetByUid(r.Uid)
	if err != nil {
		return nil, err
	}
	return &proto.UserInfoResponse{
		Uid:       user.Uid,
		NickName:  user.NickName,
		HeaderImg: user.HeaderImg,
	}, nil
}

func (s *UserServer) GetUserInfoList(ctx context.Context, request *proto.UserInfoListRequest) (*proto.UserInfoListResponse, error) {
	users, err := store.GetUserStore().GetByUids(request.Uids)
	if err != nil {
		return nil, err
	}
	response := proto.UserInfoListResponse{}
	userList := make([]*proto.UserInfoResponse, 0)
	for _, user := range users {
		userList = append(userList, &proto.UserInfoResponse{
			Uid:       user.Uid,
			NickName:  user.NickName,
			HeaderImg: user.HeaderImg,
		})
	}
	response.List = userList
	return &response, nil
}

func (s *UserServer) GetUserFollowList(ctx context.Context, request *proto.UserFollowListRequest) (*proto.UserInfoListResponse, error) {
	list, err := service.ServiceUserInstance.GetFollowList(request.Uid)
	if err != nil {
		return nil, err
	}

	var uids []int64
	for _, follow := range list {
		uids = append(uids, follow.FollowUid)
	}

	users, err := store.GetUserStore().GetByUids(uids)
	if err != nil {
		return nil, err
	}

	response := proto.UserInfoListResponse{}
	userList := make([]*proto.UserInfoResponse, 0)
	for _, user := range users {
		userList = append(userList, &proto.UserInfoResponse{
			Uid:       user.Uid,
			NickName:  user.NickName,
			HeaderImg: user.HeaderImg,
		})
	}
	response.List = userList

	return &response, nil
}
